//201902104003邵潇漩
package bysj.dao;
import bysj.domain.authority.Actor;
import bysj.domain.User;
import bysj.domain.authority.Resource;
import bysj.domain.authority.Role;
import bysj.service.ActorService;
import util.JdbcHelper;
import util.TokenHelper;

import java.sql.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.HashMap;
import java.util.TreeSet;

public final class UserDao {
    private static UserDao userDao = new UserDao();

   /* static {
        TeacherDao teacherDao = TeacherDao.getInstance();
        try{
        users = new TreeSet<User>();
        User user = new User(1, "st", "st", new Date(), teacherDao.find(1));
        users.add(user);
        users.add(new User(2, "lx", "lx", new Date(), teacherDao.find(2)));
        users.add(new User(3, "wx", "wx", new Date(), teacherDao.find(3)));
        users.add(new User(4, "lf", "lf", new Date(), teacherDao.find(4)));
        }catch (Exception e){
            e.printStackTrace();
        }
    }*/

    private UserDao() {
    }

    public static UserDao getInstance() {
        return userDao;
    }

    /*private static void display(Collection<User> users) {
        for (User user : users) {
            System.out.println(user);
        }
    }*/

    public Collection<User> findAll() throws SQLException{
        Collection<User> desiredUsers=new TreeSet<User>();
        Connection conn = JdbcHelper.getConn();
        User user=null;
        String sql_select_all="SELECT*FROM user";
        PreparedStatement pstmt = conn.prepareStatement(sql_select_all);
        ResultSet resultSet=pstmt.executeQuery();
        while (resultSet.next()){
            int id=resultSet.getInt("id");
            String username=resultSet.getString("username");
            String password= resultSet.getString("password");
            int actorId=resultSet.getInt("actor_id");
            //日期格式化
            DateTimeFormatter formatter= DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            //时间格式转换
            LocalDateTime loginTime = LocalDateTime.parse(resultSet.getString("lastLoginTime"),formatter);
           // user=new User(id,username,password,loginTime,actorId);
            desiredUsers.add(user);
        }
        JdbcHelper.close(resultSet,pstmt,conn);
        return desiredUsers;
    }

    public User find(Integer id,Connection conn)throws SQLException {
        //创建User对象
        User user=null;
        //创建sql语句
        String selectUser_sql="select * from user WHERE id=?";
        //在该连接上创建预编译语句对象
        PreparedStatement pstmt=conn.prepareStatement(selectUser_sql);
        //为预编译参数赋值
        pstmt.setInt(1,id);
        //执行SQL语句并获得结果集对象
        ResultSet resultSet=pstmt.executeQuery();
        //若结果集仍然有下一条记录，则执行循环体
        while (resultSet.next()) {
            int id1=resultSet.getInt("id");
            String username=resultSet.getString("username");
            String password = resultSet.getString("password");
            int actorId=resultSet.getInt("actor_id");
            //日期格式化
            DateTimeFormatter formatter= DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            //时间格式转换
            LocalDateTime loginTime = LocalDateTime.parse(resultSet.getString("lastLoginTime"),formatter);
           // user=new User(id1,username,password,loginTime,actorId);
        }
        //返回school对象
        return user;
    }

    public boolean update(User user,Connection connection)throws SQLException {
        //创建sql语句
        String updateUser_sql = "UPDATE user SET username=?, password=?, actor_id=? WHERE id=?";
        //在该连接上创建预编译语句对象
        PreparedStatement pstmt = connection.prepareStatement(updateUser_sql);
        //为预编译参数赋值
        pstmt.setString(1,user.getUsername());
        pstmt.setString(2,user.getPassword());
        pstmt.setInt(3,user.getActor().getId());
        pstmt.setInt(4,user.getId());
        //执行预编译语句的executeUpdate方法,获得修改的记录行数
        int affectedRowNum=pstmt.executeUpdate();
        JdbcHelper.close(null,pstmt);
        //返回school对象是否修改成功
        return affectedRowNum>0;
    }
/*
    public int add(User user, Connection connection) throws SQLException {
        //创建语句对象，字段lastLoginTime为“时间戳”类型，无须手动写入
        PreparedStatement pstmt=connection.prepareStatement("INSERT INTO user"+" (username,password,teacher_id)"+" VALUES(?,?,?)", Statement.RETURN_GENERATED_KEYS);
        pstmt.setString(1,user.getUsername());
        pstmt.setString(2,user.getPassword());
        pstmt.setInt(3,user.getTeacher().getId());
        //执行语句
        int rowAffected=pstmt.executeUpdate();
        int idOfAddedUser=0;
        //获得生成的主键集合
        ResultSet resultSet=pstmt.getGeneratedKeys();
        if (resultSet.next()){
            //读取第一个主键
            idOfAddedUser=resultSet.getInt(1);
        }
        JdbcHelper.close(resultSet,pstmt);
        //本方法是事务的一部分，不能释放资源
        return idOfAddedUser;
    }*/
    public boolean add(User user, Connection connection) throws SQLException {
        //创建语句对象, 字段lastLoginTime 为“时间戳”类型，无须手动写入
        PreparedStatement pstmt =
                connection.prepareStatement("INSERT INTO user " +
                        " (username,password,actor_id)" +
                        " VALUES(?,?,?)");
        pstmt.setString(1, user.getUsername());
        pstmt.setString(2, user.getPassword());
        pstmt.setInt(3, user.getActor().getId());

        //执行语句
        int rowAffected = pstmt.executeUpdate();
        //事务未结束，不能释放资源
        return rowAffected > 0;
    }

   /* public boolean delete(Integer id) {
        User user = this.find(id);
        return this.delete(user);
    }

    public boolean delete(User user) {
        return users.remove(user);
    }*/
   public Actor login(Connection connection, User user) throws SQLException {
       //创建Teacher类型的引用，暂不创建对象
       Actor currentActor = null;
       String sql_login = "SELECT * FROM user WHERE username =? and password=?";
       PreparedStatement pstmt_login =
               connection.prepareStatement(sql_login);
       pstmt_login.setString(1, user.getUsername());
       pstmt_login.setString(2, user.getPassword());
       ResultSet resultSet_login = pstmt_login.executeQuery();
       //如果表中存在id对应的记录，则获得表中的actor_id，并获得对应的Actor对象
       if (resultSet_login.next()) {
           int actor_id = resultSet_login.getInt("actor_id");
           currentActor = ActorService.getInstance().find(actor_id);
       }
       return currentActor;
   }
}
